namespace DependencyAnalysis.Algorithms.SubstringDetection
{
    public class Suffix
    {
        public Node OriginNode { get; private set; }
        public int BeginIndex { get; set; }
        public int EndIndex { get; set; }

        public Suffix(Node originNode, int beginIndex, int endIndex)
        {
            OriginNode = originNode;
            BeginIndex = beginIndex;
            EndIndex = endIndex;
        }

        public bool IsExplicit()
        {
            return BeginIndex > EndIndex;
        }

        public void Canonize()
        {
            if (IsExplicit()) return;
            Edge edge = OriginNode.FindEdge(OriginNode[BeginIndex]);

            int edgeSpan = edge.GetSpan();
            while (edgeSpan <= GetSpan())
            {
                BeginIndex += edgeSpan + 1;
                OriginNode = edge.EndNode;
                if (IsExplicit()) continue;
                edge = edge.EndNode.FindEdge(OriginNode[BeginIndex]);
                edgeSpan = edge.GetSpan();
            }
        }

        public int GetSpan()
        {
            return EndIndex - BeginIndex;
        }

        public void ChangeOriginNode()
        {
            OriginNode = OriginNode.SuffixNode;
        }
    }
}